#!/usr/bin/env bash

# Copyright (C) 2018 Akhil Narang
# Copyright (C) 2018 Harsh Shandilya <msfjarvis@gmail.com>
# SPDX-License-Identifier: GPL-3.0-only
# Kernel release script

# shellcheck disable=SC1090,SC2029
# SC1090: Can't follow non-constant source. Use a directive to specify location.
# SC2029: Note that, unescaped, this expands on the client side.

source ~/scripts/functions

[[ -z ${DEVICE} ]] && { [[ "$(pwd)" =~ "beryllium" ]] || [[ $* =~ "beryllium" ]]; } && DEVICE=beryllium
[[ -z ${DEVICE} ]] && DEVICE=beryllium

function tg() {
    case "${DEVICE}" in
        "beryllium")
            sendKernelBeryllium "${@:?}"
            ;;
    esac
}

SERVER="ssh.packet.resurrectionremix.com"
DOWNLOAD_HOST="https://downloads.akhilnarang.dev"
MIRROR_HOST="https://mirror.akhilnarang.dev"
KERNEL_PATH="kernel/${DEVICE}"
NAME=$(ssh "${SERVER}" ls mirror/"${KERNEL_PATH}"/Test/*.zip | tail -1)
ILLUSIONVERSION="${1:?}"
TAG="Illusion-v${ILLUSIONVERSION}"
RELEASE_ZIPNAME="${TAG}.zip"
CHANGELOG="${2}"

tg "Releasing Illusion v$ILLUSIONVERSION"
tg "Illusion v$ILLUSIONVERSION is up, grab it [here](${DOWNLOAD_HOST}/${KERNEL_PATH}/Stable/${RELEASE_ZIPNAME}) or [here](${MIRROR_HOST}/${KERNEL_PATH}/Stable/${RELEASE_ZIPNAME})"
ssh "${SERVER}" "cp -v ${NAME} mirror/${KERNEL_PATH}/Stable/${RELEASE_ZIPNAME}; cd mirror/${KERNEL_PATH}/Stable; md5sum ${RELEASE_ZIPNAME} > ${RELEASE_ZIPNAME}.md5sum"
ssh "${SERVER}" ./bin/mirrorsync
tg "Changelog:
\`\`\`
${CHANGELOG}
\`\`\`"

cd "${KERNELDIR}/${DEVICE}" || exit 1
git tag -as "${TAG}" -m "${CHANGELOG}"
git p origin "${TAG}"
cd /tmp || exit 1
wget "${DOWNLOAD_HOST}/${KERNEL_PATH}/Stable/${RELEASE_ZIPNAME}"
wget "${DOWNLOAD_HOST}/${KERNEL_PATH}/Stable/${RELEASE_ZIPNAME}.md5sum"
cd - || exit 1
hub release create "${TAG}" -a "/tmp/${RELEASE_ZIPNAME}" -a "/tmp/${RELEASE_ZIPNAME}.md5sum" -m "Illusion v${1} release"
rm "/tmp/${RELEASE_ZIPNAME}" "/tmp/${RELEASE_ZIPNAME}.md5sum"
tg "${TAG} released!"
